package Dao.impl;

import Dao.SalaryDao;
import Domin.Salary;
import Utils.ConnectionUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SalaryDaoImpl implements SalaryDao {

    @Override
    public boolean saveSalary(Salary salary) {
        String sql = "INSERT INTO salary(emp_id, base_salary, bonus, total, month) VALUES(?, ?, ?, ?, ?)";
        try (Connection con = ConnectionUtil.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setInt(1, salary.getEmpId());
            ps.setDouble(2, salary.getBaseSalary());
            ps.setDouble(3, salary.getBonus());
            ps.setDouble(4, salary.getTotal());
            ps.setString(5, salary.getMonth());
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Salary> getSalariesByEmpId(int empId) {
        List<Salary> list = new ArrayList<>();
        String sql = "SELECT salary_id, emp_id, base_salary, bonus, total, month FROM salary WHERE emp_id = ?";
        try (Connection con = ConnectionUtil.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setInt(1, empId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Salary s = new Salary();
                    s.setSalaryId(rs.getInt("salary_id"));
                    s.setEmpId(rs.getInt("emp_id"));
                    s.setBaseSalary(rs.getDouble("base_salary"));
                    s.setBonus(rs.getDouble("bonus"));
                    s.setTotal(rs.getDouble("total"));
                    s.setMonth(rs.getString("month"));
                    list.add(s);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Salary> getAllSalaries() {
        List<Salary> list = new ArrayList<>();
        String sql = "SELECT salary_id, emp_id, base_salary, bonus, total, month FROM salary";
        try (Connection con = ConnectionUtil.getConnection();
             PreparedStatement ps = con.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                Salary s = new Salary();
                s.setSalaryId(rs.getInt("salary_id"));
                s.setEmpId(rs.getInt("emp_id"));
                s.setBaseSalary(rs.getDouble("base_salary"));
                s.setBonus(rs.getDouble("bonus"));
                s.setTotal(rs.getDouble("total"));
                s.setMonth(rs.getString("month"));
                list.add(s);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}